
import { useEffect, useRef, useState } from "react";
import Game from "./Game";
import { debounce, throttle } from 'lodash';

function useGamePad(): { button: number, timestamp: number } {
    const [state, _setState] = useState({
        button: '',
        timestamp: 0
    });
    const setState = (params: { [key: string]: any }) => {
        _setState((_state) => ({ ..._state, ...params }));
    };
    const { button, timestamp } = state;
    const game: { current: Game } = useRef() as any
    const init = () => {
        game.current = new Game({
            update: debounce((index: number, _t) => {
                setState({
                    button: index,
                    timestamp: _t
                })
            }, 50),
            connect: (_t: number) => {
                setState({ timestamp: _t })
            }
        });
    }
    useEffect(() => {
        init();
        console.log('init')
        window.addEventListener("gamepadconnected", game.current.connect);
        window.addEventListener("gamepaddisconnected", game.current.disconnect);
        return () => {
            window.removeEventListener("gamepadconnected", game.current.connect);
            window.removeEventListener("gamepaddisconnected", game.current.disconnect);
            game.current = null as any;
        }
    }, [])
    return { timestamp, button };
}

export default useGamePad;